package com.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tanhua.autoconfig.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author: Liking
 * @description
 * @date: 2023/7/24 16:40
 */
@Slf4j
public class OssTemplate {
    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {

        this.ossProperties = ossProperties;
    }

    /**
     * 文件上传
     * @param fileName 文件名称
     * @param is 输入流
     * @return
     */
    public String upload(String fileName, InputStream is) {
        //1.拼写图片路径
        fileName = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        //2.上传到阿里云OSS
        //2.1获得OSS对象的地域信息
        String endpoint = ossProperties.getEndpoint();
        //2.2获得OSS对象的RAM账号
        String accessKeyId = ossProperties.getAccessKey();
        //2.3获得OSS对象的RAM密码
        String accessKeySecret = ossProperties.getSecret();
        //3.创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //4.上传文件流
        ossClient.putObject(ossProperties.getBucketName(), fileName, is);

        //5.关闭OSSClient
        ossClient.shutdown();

        //6.返回url地址
        return ossProperties.getUrl() +"/" +fileName;
    }
}
